﻿using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.WebHelpers;
using mojoPortal.Web.Framework;
using mojoPortal.Web;
using Resources;
using ud_Article.Business;
using System.Configuration;
using ud_Utilities;

namespace ud_Article.UI
{
    public partial class AdminPostList : UserControl
    {
        #region Properties

        private int countOfDrafts;
        private int pageNumber = 1;
        private int totalPages = 1;
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string DeletePostAltText = "Delete";
        protected string EditBlogAltText = "Edit";
        protected Double TimeOffset;
        private TimeZoneInfo timeZone;
        protected DateTime CalendarDate;
        protected bool ShowGoogleMap = true;
        protected string FeedBackLabel = string.Empty;
        protected string GmapApiKey = string.Empty;
        protected bool EnableContentRating;
        protected string disqusFlag = string.Empty;
        protected string IntenseDebateAccountId = string.Empty;
        protected bool ShowCommentCounts = true;
        protected string EditLinkText = ArticleResources.BlogEditEntryLink;
        protected string EditLinkTooltip = ArticleResources.BlogEditEntryLink;
        protected string EditLinkImageUrl = string.Empty;
        protected string DeleteLinkText = ArticleResources.ArticleDeleteLinkText;
        protected string DeleteLinkTooltip = ArticleResources.ArticleDeleteLinkText;
        protected string DeleteLinkImageUrl = string.Empty;
        private mojoBasePage basePage;
        private Module module;
        protected ArticleConfiguration config = new ArticleConfiguration();

        private int pageId = -1;
        private int moduleId = -1;
        private string siteRoot = string.Empty;
        private string imageSiteRoot = string.Empty;
        private SiteSettings siteSettings;
        private PageSettings currentPage;

        public AdminPostList()
        {
            IsEditable = false;
        }

        public int PageId
        {
            get { return pageId; }
            set { pageId = value; }
        }

        public int ModuleId
        {
            get { return moduleId; }
            set { moduleId = value; }
        }

        public string SiteRoot
        {
            get { return siteRoot; }
            set { siteRoot = value; }
        }

        public string ImageSiteRoot
        {
            get { return imageSiteRoot; }
            set { imageSiteRoot = value; }
        }

        public ArticleConfiguration Config
        {
            get { return config; }
            set { config = value; }
        }

        public bool IsEditable { get; set; }

        public PageSettings CurrentPage
        {
            get { return currentPage ?? (currentPage = CacheHelper.GetCurrentPage()); }
        }

        #endregion


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            calBlogNav.SelectionChanged += calBlogNav_SelectionChanged;
            calBlogNav.VisibleMonthChanged += CalBlogNavVisibleMonthChanged;
            //pgr.Command += new CommandEventHandler(pgr_Command);
            EnableViewState = true;
            rptBlogs.ItemDataBound += rptBlogs_ItemDataBound;
            rptBlogs.ItemCommand += rptBlogs_ItemCommand;
        }




        protected virtual void Page_Load(object sender, EventArgs e)
        {
            LoadParams();
            LoadSettings();

#if !MONO
            if (!(Page is mojoPortal.Web.UI.Pages.MyPage))
            {
                SetupRssLink();
            }
#endif
            PopulateLabels();
            if (!Page.IsPostBack)
            {
                PopulateControls();
            }


        }

        private void PopulateControls()
        {
            BindBlogs();
            PopulateNavigation();
        }

        private void BindBlogs()
        {
            int adminPageSize = int.Parse(ConfigurationManager.AppSettings["ArticleAdminPageSize"]);
            using (IDataReader reader = Article.GetPage(ModuleId, CalendarDate.Date.AddDays(1), pageNumber, adminPageSize, out totalPages))
            {
                rptBlogs.DataSource = reader;
                rptBlogs.DataBind();

                string pageUrl = SiteRoot + "/Article/ManagePost.aspx"
                   + "?pageid=" + pageId.ToInvariantString()
                   + "&amp;mid=" + moduleId.ToInvariantString()
                   + "&amp;pagenumber={0}";

                pgr.PageURLFormat = pageUrl;
                pgr.ShowFirstLast = true;
                pgr.PageSize = adminPageSize;
                pgr.PageCount = totalPages;
                pgr.CurrentIndex = pageNumber;
                pnlBlogPager.Visible = totalPages > 1;
            }
        }

        //void pgr_Command(object sender, CommandEventArgs e)
        //{
        //    pageNumber = Convert.ToInt32(e.CommandArgument);
        //    pgr.CurrentIndex = pageNumber;
        //    PopulateControls();
        //    updBlog.Update();
        //}

        protected virtual void PopulateNavigation()
        {
            Feeds.Config = config;
            Feeds.PageId = PageId;
            Feeds.ModuleId = ModuleId;
            Feeds.Visible = config.ShowFeedLinks;

            tags.CanEdit = IsEditable;
            tags.PageId = PageId;
            tags.ModuleId = ModuleId;
            tags.SiteRoot = SiteRoot;
            tags.RenderAsTagCloud = config.UseTagCloudForCategories;

            archive.PageId = PageId;
            archive.ModuleId = ModuleId;
            archive.SiteRoot = SiteRoot;

            stats.PageId = PageId;
            stats.ModuleId = ModuleId;
            stats.CountOfDrafts = countOfDrafts;
            stats.Visible = config.ShowStatistics;

        }

        private void calBlogNav_SelectionChanged(object sender, EventArgs e)
        {
            System.Web.UI.WebControls.Calendar cal = (System.Web.UI.WebControls.Calendar)sender;

            CalendarDate = cal.SelectedDate;
            //calBlogNav.VisibleDate = CalendarDate;
            //calBlogNav.SelectedDate = CalendarDate;
            //PopulateControls();

            RedirectFromCalendar();

        }

        private void CalBlogNavVisibleMonthChanged(object sender, MonthChangedEventArgs e)
        {
            CalendarDate = e.NewDate;
            //calBlogNav.VisibleDate = CalendarDate;
            //calBlogNav.SelectedDate = CalendarDate;
            //PopulateControls();

            RedirectFromCalendar();

        }

        private void RedirectFromCalendar()
        {
            string pageUrl = SiteRoot + "/Article/ViewList.aspx"
                   + "?pageid=" + pageId.ToInvariantString()
                   + "&mid=" + moduleId.ToInvariantString()
                   + "&blogdate=" + CalendarDate.Date.ToString("s");

            WebUtils.SetupRedirect(this, pageUrl);

        }




        protected virtual void PopulateLabels()
        {

            calBlogNav.UseAccessibleHeader = true;

            EditBlogAltText = ArticleResources.EditImageAltText;
            FeedBackLabel = ArticleResources.BlogFeedbackLabel;

            mojoBasePage mojoBasePage = Page as mojoBasePage;
            if (mojoBasePage != null)
            {
                if (!mojoBasePage.UseTextLinksForFeatureSettings)
                {
                    EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                    DeleteLinkImage = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
                }

            }

        }

        protected string FormatPostAuthor(string authorName)
        {
            if (config.ShowPostAuthor)
            {
                if (config.BlogAuthor.Length > 0)
                {
                    return string.Format(CultureInfo.InvariantCulture, ArticleResources.PostAuthorFormat, config.BlogAuthor);
                }

                return string.Format(CultureInfo.InvariantCulture, ArticleResources.PostAuthorFormat, authorName);
            }

            return string.Empty;

        }

        protected string FormatBlogEntry(string blogHtml, string excerpt, string url, int itemId)
        {
            if (config.UseExcerpt)
            {
                if ((excerpt.Length > 0) && (excerpt != "<p>&#160;</p>"))
                {
                    return excerpt + config.ExcerptSuffix + " <a href='" + FormatBlogUrl(url, itemId) + "' class='morelink'>" + config.MoreLinkText + "</a><div>&nbsp;</div>";
                }
                blogHtml = SecurityHelper.RemoveMarkup(blogHtml);
                if ((blogHtml.Length > config.ExcerptLength) && (config.MoreLinkText.Length > 0))
                {

                    string result = UIHelper.CreateExcerpt(blogHtml, config.ExcerptLength, config.ExcerptSuffix);
                    result += " <a href='" + FormatBlogTitleUrl(url, itemId) + "' class='morelink'>" + config.MoreLinkText + "</a><div>&nbsp;</div>";
                    return result;
                }
            }
            return blogHtml;
        }

        protected string FormatBlogDate(DateTime startDate)
        {
            if (config.DateTimeFormat == string.Empty) return string.Empty;
            return timeZone != null ? TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString(config.DateTimeFormat) : startDate.AddHours(TimeOffset).ToString(config.DateTimeFormat);
        }

        protected string FormatBlogUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty) + disqusFlag;

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString()
                + disqusFlag;

        }

        protected string FormatBlogTitleUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + PageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + ModuleId.ToInvariantString();

        }

        private string GetRssUrl()
        {
            if (config.FeedburnerFeedUrl.Length > 0) return config.FeedburnerFeedUrl;

            return SiteRoot + "/blog" + ModuleId.ToInvariantString() + "rss.aspx";

        }

        protected void DeletePost(int itemID)
        {
            Article article = new Article(itemID);
            DeleteImageFromServer(article);
            article.ContentChanged += article_ContentChanged;
            article.Delete();
            FriendlyUrl.DeleteByPageGuid(article.BlogGuid);
            CurrentPage.UpdateLastModifiedTime();
            SiteUtils.QueueIndexing();
            WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
        }

        private void DeleteImageFromServer(Article article)
        {
            string thumbnailImageURL = Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["ArticleImagesFolder"] + article.ImageUrl;
            thumbnailImageURL = thumbnailImageURL.Replace("/", "\\");
            string imageURL = thumbnailImageURL.Substring(0, thumbnailImageURL.LastIndexOf(".")) + "_t" + thumbnailImageURL.Substring(thumbnailImageURL.LastIndexOf("."));
            if (File.Exists(imageURL))
            {
                File.Delete(imageURL);
            }
            if (File.Exists(thumbnailImageURL))
            {
                File.Delete(thumbnailImageURL);
            }
        }

        protected virtual void LoadSettings()
        {
            siteSettings = CacheHelper.GetCurrentSiteSettings();
            TimeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            GmapApiKey = SiteUtils.GetGmapApiKey();
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", pageNumber);

            if (Page is mojoBasePage)
            {
                basePage = Page as mojoBasePage;
                module = basePage.GetModule(moduleId);
            }

            CalendarDate = WebUtils.ParseDateFromQueryString("blogdate", DateTime.UtcNow).Date;

            if (CalendarDate > DateTime.UtcNow.Date)
            {
                CalendarDate = DateTime.UtcNow.Date;
            }

            if ((config.UseExcerpt) && (!config.GoogleMapIncludeWithExcerpt))
            {
                ShowGoogleMap = false;
            }

            EnableContentRating = config.EnableContentRating;
            if (config.UseExcerpt)
            {
                EnableContentRating = false;
            }

            IntenseDebateAccountId = config.IntenseDebateAccountId.Length > 0 ? config.IntenseDebateAccountId : siteSettings.IntenseDebateAccountId;

            calBlogNav.Visible = true;
            try
            {
                calBlogNav.FirstDayOfWeek = (FirstDayOfWeek) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
            }
            catch (ArgumentNullException)
            {
            }
            catch (ArgumentOutOfRangeException)
            {
            }
            catch (InvalidOperationException)
            {
            }
            catch (InvalidCastException)
            {
            }

            if (!Page.IsPostBack)
            {
                calBlogNav.SelectedDate = CalendarDate;
                calBlogNav.VisibleDate = CalendarDate;

            }


            if (config.Copyright.Length > 0)
            {
                lblCopyright.Text = config.Copyright;
            }

            pnlStatistics.Visible = config.ShowStatistics;


            divNav.Visible = true;

            if (!divNav.Visible)
            {
                divblog.CssClass = "blogcenter-nonav";
            }
            if (IsEditable)
            {
                countOfDrafts = Article.CountOfDrafts(ModuleId);
            }
        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", pageNumber);

        }

        protected virtual void SetupRssLink()
        {
            if (WebConfigSettings.DisableBlogRssMetaLink) { return; }

            if (module != null)
            {
                if (Page.Master != null)
                {
                    Control head = Page.Master.FindControl("Head1");
                    if (head != null)
                    {

                        Literal rssLink = new Literal
                                              {
                                                  Text = @"<link rel=""alternate"" type=""application/rss+xml"" title="""
                                                         + module.ModuleTitle + @""" href="""
                                                         + GetRssUrl() + @""" />"
                                              };

                        head.Controls.Add(rssLink);
                    }
                }
            }

        }

        void rptBlogs_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (!e.Item.ItemType.Equals(ListItemType.Item) && !e.Item.ItemType.Equals(ListItemType.AlternatingItem))
                return;
            ImageButton ibtnDelete = e.Item.FindControl("ibtnDelete") as ImageButton;
            Utilities.AddConfirmButton(ibtnDelete, ArticleResources.DeleteConfirmation);
        }

        void rptBlogs_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (!e.CommandName.Equals("Delete")) return;
            Article article = new Article(int.Parse(e.CommandArgument.ToString()));
            if (!article.ImageUrl.Equals(string.Empty))
            {
                DeleteImageFromServer(article);
            }
            article.ContentChanged += article_ContentChanged;
            article.Delete();
            FriendlyUrl.DeleteByPageGuid(article.BlogGuid);
            CurrentPage.UpdateLastModifiedTime();
            SiteUtils.QueueIndexing();
            //BindBlogs();
            //WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
            WebUtils.SetupRedirect(this, Request.Url.ToString());
        }

        void article_ContentChanged(object sender, ContentChangedEventArgs e)
        {
            IndexBuilderProvider indexBuilder = IndexBuilderManager.Providers["ArticleIndexBuilderProvider"];
            if (indexBuilder != null)
            {
                indexBuilder.ContentChangedHandler(sender, e);
            }
        }

    }
}